<template>
  <div
    class="modal"
    @click.self="$emit('close')"
  >
    <!-- 点击模态框外部关闭模态框 -->
    <div class="modal-content">
      <span
        class="close"
        @click="$emit('close')"
      >&times;</span>
      <!-- 关闭按钮 -->
      <div class="modal-body">
        <!-- <img
          v-if="post.image"
          :src="`http://localhost:5000/uploads/${post.image}`"
          class="modal-image"
        /> -->
        <!-- 显示帖子图片 -->
        <!-- <img v-else src="../assets/default.jpg" class="modal-image" /> -->
        <div class="modal-image-container">
          <img
            v-if="post.image"
            :src="`http://localhost:5000/uploads/${post.image}`"
            class="modal-image"
          />
        </div>
        <!-- 显示默认图片 -->
        <div class="modal-details">

            <div class="author-wrapper">
              <img
                :src="post.authorimg
                    ? `http://localhost:5000/uploads/${post.authorimg}`
                    : '../assets/touxiang.png'
                  "
                alt="Author Avatar"
                class="author-avatar"
              />
              <div class="author-info">
                <span class="author">{{ post.author }}</span>
                <span class="author-time">{{ authorTime(post.createdAt) }}</span>
              </div>
              <!-- 显示帖子作者 -->
            </div>

          <div class="modal-details-container">
            <h4 class="modal-title">{{ post.title }}</h4>
            <!-- 显示帖子标题 -->
            <p class="modal-description">{{ post.description }}</p>
            <!-- 显示帖子描述 -->

            <div class="comments-section">
              <div class="comments-list">
                <div
                  v-for="comment in sortedComments"
                  :key="comment.id"
                  class="comment-item"
                >
                  <div class="comment-content">
                    <div class="comment-header">
                      <img
                      :src="comment.avatar
                    ? `http://localhost:5000/uploads/${comment.avatar}`
                    : '../assets/touxiang.png'
                  "
                        alt="Avatar"
                        class="comment-avatar"
                      />
                    </div>
                    <div class="comment-info">
                      <span class="comment-username">{{ comment.username }}</span>
                      <div class="comment-text">{{ comment.text }}</div>
                      <span class="comment-time">{{
                        formatCommentTime(comment.createdAt)
                        }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="rightfooter">
            <div class="comment-input-wrapper">
              <input
                v-model="newComment"
                placeholder="添加评论..."
                class="comment-input"
              />
              <!-- 输入框用于添加新评论 -->
              <button
                @click="addComment"
                class="submit-button"
              >提交</button>
              <!-- 提交评论按钮 -->
            </div>
            <div
              class="like-wrapper"
              @click.stop="toggleLike"
            >
              <!-- 点赞功能 -->
              <img
                :src="isLiked ? zaned : zan"
                alt="点赞"
                class="like-icon"
                :class="{ liked: isLiked }"
              />
              <!-- 点赞图标 -->
              <span>{{ likeCount }}</span>
              <!-- 显示点赞数 -->
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from "vue";
import ElementPlus from "element-plus";
import { formatDistanceToNow, format } from "date-fns";
import { zhCN } from "date-fns/locale";
import axios from "axios";
import { ElMessage } from "element-plus";
import zaned from "../assets/zaned.png";
import zan from "../assets/zan.png";
const props = defineProps({
  post: Object,
});
const emit = defineEmits(["close", "update:post"]);
const newComment = ref("");
const isLiked = ref(props.post.isLiked);
const likeCount = ref(props.post.likedBy?.length || 0);
const isLoadingLike = ref(false);
const isLoadingComment = ref(false);

// 计算属性，用于对评论进行排序
const sortedComments = computed(() => {
  if (!props.post || !props.post.comments) {
    return [];
  }
  // 复制数组以避免修改原始 prop
  const commentsCopy = [...props.post.comments];
  // 按 createdAt 降序排序（最新的在前）
  return commentsCopy.sort((a, b) => {
    const dateA = new Date(a.createdAt).getTime();
    const dateB = new Date(b.createdAt).getTime();
    // 处理无效日期
    if (isNaN(dateA)) return 1;
    if (isNaN(dateB)) return -1;
    return dateB - dateA;
  });
});

console.log("Initial state:", {
  post: props.post,
  postLikes: props.post.likedBy?.length,
  postLiked: props.post.likedBy,
  localLikeCount: likeCount.value,
  localIsLiked: isLiked.value,
});

async function toggleLike () {
  if (isLoadingLike.value) return;
  isLoadingLike.value = true;

  try {
    const token = localStorage.getItem("token");
    if (!token) {
      ElMessage.warning("请先登录");
      isLoadingLike.value = false;
      return;
    }

    const response = await axios.put(
      `http://localhost:5000/posts/${props.post._id}/like`,
      {},
      {
        headers: { Authorization: `Bearer ${token}` },
      }
    );

    isLiked.value = response.data.isLiked;
    likeCount.value = response.data.likes;

    emit("update:post", {
      ...props.post,
      likes: likeCount.value,
      isLiked: isLiked.value,
    });
  } catch (error) {
    console.error("点赞/取消点赞失败:", error);
    ElMessage.error(
      "操作失败: " + (error.response?.data?.message || error.message)
    );
  } finally {
    isLoadingLike.value = false;
  }
}

async function addComment () {
  if (!newComment.value.trim() || isLoadingComment.value) return;
  isLoadingComment.value = true;

  try {
    const token = localStorage.getItem("token");
    if (!token) {
      ElMessage.warning("请先登录");
      isLoadingComment.value = false;
      return;
    }

    const response = await axios.post(
      `http://localhost:5000/posts/${props.post._id}/comments`,
      { text: newComment.value },
      {
        headers: { Authorization: `Bearer ${token}` },
      }
    );

    const addedComment = response.data.comment;
    const formattedComment = {
      ...addedComment,
      avatarUrl: addedComment.avatar
        ? `http://localhost:5000/uploads/${addedComment.avatar}`
        : null,
    };
    if (!props.post.comments) {
      props.post.comments = [];
    }
    props.post.comments.push(formattedComment);
    newComment.value = "";
  } catch (error) {
    console.error("添加评论失败:", error);
    ElMessage.error(
      "操作失败: " + (error.response?.data?.message || error.message)
    );
  } finally {
    isLoadingComment.value = false;
  }
}

function formatCommentTime (dateString) {
  if (!dateString) return "未知时间";
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
       console.error("无法解析的评论日期值:", dateString);
       return "无效日期";
    }
    return formatDistanceToNow(date, {
      addSuffix: true,
      locale: zhCN,
    });
  } catch (e) {
    console.error("格式化评论日期时出错:", dateString, e);
    return "日期格式错误";
  }
}

function authorTime (dateString) {
  if (!dateString) return "未知时间";
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) {
       console.error("无法解析的作者日期值:", dateString);
       return "无效日期";
    }
    return format(date, "yyyy-MM-dd HH:mm");
  } catch (e) {
    console.error("格式化作者日期时出错:", dateString, e);
    return "日期格式错误";
  }
}
</script>

<style scoped>
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.modal-content {
  background-color: #2a2a2a;
  padding: 30px;
  border-radius: 16px;
  max-width: 80vw;
  /* min-width: 40vw; */
  width: auto;
  height: 600px;
  position: relative;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.close {
  position: absolute;
  top: 10px;
  right: 20px;
  cursor: pointer;
  font-size: 40px;
  color: #ffffff;
  opacity: 0.8;
  transition: opacity 0.3s ease;
}

.close:hover {
  opacity: 1;
}

.modal-body {
  display: flex;
  flex: 1;
  gap: 30px;
}

.modal-image-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  /* flex-shrink: 0; 添加: 防止容器收缩 */
}

.modal-image {
  max-width: 730px;
  max-height: 600px;
  height: auto;
  border-radius: 12px;
  object-fit: cover;
}

.modal-details {
  min-width: 300px;
  max-width: 300px;
  height: 600px;
  display: flex;
  flex-direction: column;
  color: #ffffff;
  overflow: hidden;
  overflow-y: auto;
  flex-shrink: 0; /* 添加: 防止详情区收缩 */

}

.modal-details-container {
  display: flex;
  flex-grow: 1;
  margin-bottom: 10px;
  flex-direction: column;
  transition: scroll 0.3s ease !important;
  overflow-y: scroll !important;

}

.modal-title {
  margin: 0;
  font-size: 1.5em;
  font-weight: bold;
  color: #ffffff;
}

.modal-description {
  margin: 15px 0;
  text-align: justify;
  max-width: 380px;
  /* overflow-y: auto; */
  color: #b0bec5;
  line-height: 1.6;
  font-size: 14px;
}

.comments-section {
  /* margin-top: 20px; */
  /* flex: 1; */
  /* overflow-y: auto; */
}

.comments-list {
  /*滚动*/

  display: flex;
  flex-direction: column;
  gap: 10px;

  .comment-content {
    display: flex;
    flex-direction: row;
    gap: 10px;

    .comment-avatar {
      width: 30px;
      height: 30px;
      border-radius: 50%;
    }

    .comment-info {
      display: flex;
      flex-direction: column;

      .comment-username {
        font-size: 15px;
        font-weight: bold;
      }

      .comment-text {
        font-size: 14px;
      }

      .comment-time {
        font-size: 11px;
      }
    }
  }

  .comment-header {
    display: flex;
    /* align-items: center; */
    gap: 10px;
  }
}

.comment-item {
  background-color: #333333;
  padding: 12px;
  border-radius: 8px;
  color: #ffffff;
  font-size: 14px;

  p {
    margin: 0;
  }
}

.rightfooter {
  display: flex;
  flex-direction: row;
  gap: 8px;
  align-items: center;
  height: 45px;
  flex-shrink: 0;
}

.comment-input-wrapper {
  width: 80%;

  display: flex;
  gap: 8px;
}

.comment-input {
  flex: 4;
  padding: 10px 12px;
  height: 15px;
  width: 100%;
  border: 1px solid #424242;
  border-radius: 8px;
  background: #333333;
  color: #ffffff;
  font-size: 14px;
  transition: all 0.3s ease;
}

.comment-input:focus {
  border-color: #3f51b5;
  outline: none;
  box-shadow: 0 0 0 2px rgba(63, 81, 181, 0.2);
}

.submit-button {
  flex: 1;
  padding: 10px;
  height: 37px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(45deg, #3f51b5, #2196f3);
  color: #ffffff;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
}

.author-wrapper {
  height: 50px;
  display: flex;
  padding-bottom: 10px;
  border-bottom: 1px solid #424242;
  flex-shrink: 0;
}

.author-info {
  display: flex;
  flex-direction: column;
  justify-content: center;

  .author {
    color: #b0bec5;
    padding-left: 10px;
    font-size: 18px;
  }

  .author-time {
    font-size: 12px;
    color: #b0bec5;
    padding-left: 10px;
  }
}

.author-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.like-wrapper {
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #b0bec5;
  transition: all 0.3s ease;
}

/* .like-wrapper:hover {
  color: #2196f3;
} */

.like-icon {
  width: 30px;
  height: 30px;
  opacity: 0.8;
  transition: all 0.3s ease;
}

.like-wrapper:hover .like-icon {
  opacity: 1;
  transform: scale(1.1);
}

.like-icon.liked {
  opacity: 1;
  color: #2196f3;
  transform: scale(1.1);
}
</style>
